import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import Interfaces.ICommandChannel;
import Messages.CommandMessage;
import Messages.CommandTypeEnum;
import Messages.MonitorDataTypeEnum;


public class CommandChannel implements ICommandChannel
{
	private Socket m_socket;

	@Override
	public boolean Register(String agentIP, 
							int agentPort, 
							int monitorDataPort,
							MonitorDataTypeEnum monitorDataType, 
							Object[] parameters)
	{
		try 
		{
			m_socket = new Socket(InetAddress.getByName(agentIP), agentPort);
			ObjectOutputStream os = new ObjectOutputStream(m_socket.getOutputStream());
			CommandMessage comMessage = new CommandMessage();
			comMessage.MonitorDataType = monitorDataType;
			comMessage.Parameters = parameters;
			comMessage.Type = CommandTypeEnum.Register;
			comMessage.MonitorIP = InetAddress.getLocalHost().getHostAddress();
			comMessage.MonitorDataPort = monitorDataPort;
			os.flush();
			os.writeObject(comMessage);
			os.flush();
			
			return true;
		} 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		finally
		{
			try 
			{
				m_socket.close();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean Unregister(String agentIP, 
						      int agentPort,
						      MonitorDataTypeEnum monitorDataType) 
	{
		try 
		{
			m_socket = new Socket(InetAddress.getByName(agentIP), agentPort);
			ObjectOutputStream os = new ObjectOutputStream(m_socket.getOutputStream());
			CommandMessage comMessage = new CommandMessage();
			comMessage.MonitorDataType = monitorDataType;
			comMessage.Type = CommandTypeEnum.Unregister;
			comMessage.MonitorIP = InetAddress.getLocalHost().getHostAddress();
			os.flush();
			os.writeObject(comMessage);
			os.flush();
			
			return true;
		} 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		finally
		{
			try 
			{
				m_socket.close();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
}
